<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽效果</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            background-color: red;
            border-radius: 15px;
            box-shadow: 10px 10px 15px rgba(0,0,0,0.7);
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        let div = document.querySelector('div');
        let flag=false;
        div.addEventListener('mousedown',(e)=>{
           
            flag=true;
            // 获取的是 相对于目标元素的 偏移量 x,y
            let x = e.offsetX;
            let y = e.offsetY;
            document.addEventListener('mousemove',(e)=>{
                 // window.innerHeight,window.innerWidth 获取的是屏幕的分辨率大小
                 // div.offsetHeight,div.offsetWidth 获取的是div元素的宽高大小
                let _h = window.innerHeight - div.offsetHeight;
                let _w = window.innerWidth- div.offsetWidth;
                // 获取的是 相对于浏览器的 偏移量 x,y
                let div_left = e.clientX-x;
                let div_top = e.clientY-y;
                div_top = Math.min(Math.max(0,div_top),_h);
                div_left = Math.min(Math.max(0,div_left),_w);
                if(flag){
                    div.style.top=div_top+'px';
                    div.style.left=div_left+'px';
                }
                
            })
        })
        div.addEventListener('mouseup',(e)=>{
            flag = false;
        })
       
    </script>
</body>
</html>